package com.zjj.algorithm.learning.atguigu.stack;

import java.util.Scanner;

/**
 * 使用数组实现栈的功能
 * @author zjj_admin
 * @date 2022/11/8 21:32
 */
public class ArrayStackDemo {

    public static void main(String[] args) {

        // 先创建一个ArrayStack对象->表示栈
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        // 控制是否退出菜单
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);

        while (loop) {
            System.out.println("show: 表示显示栈");
            System.out.println("exit: 退出程序");
            System.out.println("push: 表示添加数据到栈(入栈)");
            System.out.println("pop: 表示从栈取出数据(出栈)");
            System.out.println("请输入你的选择");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.show();
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try {
                        int res = stack.pop();
                        System.out.printf("出栈的数据是 %d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }

        System.out.println("程序退出~~~");
    }
}


/**
 * 基于数组，定义一个栈
 */
class ArrayStack{
    private int maxSize;
    private  int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }

    public boolean isFull(){
        return this.top == this.maxSize -1;
    }

    public boolean isEmpty(){
        return top == -1;
    }

    /**
     * 入栈
     * @param value
     */
    public void push(int value){
        if (isFull()) {
            System.out.println("栈满，不能入栈");
            return;
        }
        top ++;
        stack[top] = value;
    }

    /**
     * 出栈
     * @return
     */
    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈已经空了");
        }
        int value = this.stack[top];
        top --;
        return value;
    }

    public void show(){
        if (isEmpty()) {
            System.out.println("栈中不存在数据");
            return;
        }
        for (int i = top ; i >= 0; i--){
            System.out.printf("stack[%d] = %d \n",i,stack[i]);
        }
    }
}
